<template>
  <!--经办人管理-->
  <section class="page agent-manage">
    <div class="row">
      <div class="col-span-2 org-tree" v-if="!treeClose">
        <data-tree
          @select-change="onChange"
          :props="{ title: 'deptName' }"
          default-expand-all
          :default-expanded-keys="expandDefault"
          :highlight-current="true"
          node-key="id"
          ref="orgTree"
          :data="departmentData"
          v-if="dialogVisible"
        ></data-tree>
      </div>
      <div :class="treeClose ? 'col-span-12' : 'col-span-10'">
        <data-form  :model="userModel" @onSearch="refreshData" :page="pageService">
          <template slot="inputs">
            <el-row>
              <!-- 非外包队列 -->
              <el-col :span="8">
                <el-form-item label="经办人" prop="realName" class="input-style" v-if="queueType !== 'OUTER'">
                  <el-input v-model.trim="userModel.realName" clearable :maxlength="20"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="经办编号" prop="handCode" class="input-style" v-if="queueType !== 'OUTER'">
                  <el-input v-model.trim="userModel.handCode" :maxlength="20" clearable></el-input>
                </el-form-item>
              </el-col>
              <!-- 外包队列 -->
              <el-col :span="8">
                <el-form-item label="外包公司" prop="outOrgName" class="input-style" v-if="queueType === 'OUTER'">
                  <el-input v-model.trim="userModel.outOrgName" :maxlength="20" clearable></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="外包编号" prop="divisionCode"  class="input-style" v-if="queueType === 'OUTER'">
                  <el-input v-model.trim="userModel.divisionCode" :maxlength="20" clearable></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8" v-if="isTeamUse">
                <el-form-item label="是否管理员" prop="isAdmin" class="input-style">
                  <el-select v-model="userModel.isAdmin" placeholder="请选择" clearable>
                    <el-option label="是" value="1"></el-option>
                    <el-option label="否" value="0"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
          </template>
        </data-form>
        <!-- selectAgent -->
        <data-box-page-pick
          :data="userDataSet"
          @update:selectionList="selectList"
          :selectionList.sync="selectionList"
          @onPageChange="refreshData"
          :page="pageService"
          :isTelUse="true"
          ref="data-box"
          height="500"
          v-if="dialogVisible"
          :row-key="getRowKeys"
        >
          <template slot="columns">
            <el-table-column type="selection" :reserve-selection='true' v-if="selectionList" :selectable="selectable" width="50"></el-table-column>
            <el-table-column  label="序号" type="index" width="60"></el-table-column>
            <!-- 非外包公司 -->
            <el-table-column  prop="handCode" label="经办编号" :min-width="$helper.getColumnWidth(4)" show-overflow-tooltip v-if="queueType !== 'OUTER'">
            </el-table-column>
            <el-table-column prop="realName" label="姓名" :min-width="$helper.getColumnWidth(4)" show-overflow-tooltip v-if="queueType !== 'OUTER'" >
            </el-table-column>
            <el-table-column prop="deptName" label="所属机构" :min-width="$helper.getColumnWidth(4)" show-overflow-tooltip v-if="queueType !== 'OUTER'">
            </el-table-column>
            <el-table-column prop="caseSwitch" label="分案开关"
              :min-width="$helper.getColumnWidth(4)"
              show-overflow-tooltip
              v-if="queueType !== 'OUTER'"
            >
              <template slot-scope="scope">
                <div>
                  {{scope.row.caseSwitch === 'OPEN' ? "开启" : '关闭'}}
                </div>
                <!-- {{scope.row.caseSwitch === 'OPEN' ? "关闭" : '开启'}} -->
              </template>
            </el-table-column>
            <el-table-column prop="caseSwitch" label="分案开关" 
              :min-width="$helper.getColumnWidth(4)" 
              show-overflow-tooltip 
              v-if="queueType === 'OUTER'">
              <template slot-scope="scope">
                <div>
                  {{scope.row.caseSwitch === 'OPEN' ? "开启" : '关闭'}}
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="isAdmin" label="是否管理员" :min-width="$helper.getColumnWidth(4)" :formatter="row => $filter.dictConvert(row.isAdmin, 'isAdmin')" show-overflow-tooltip v-if="queueType !== 'OUTER'">
              <template slot-scope="scope">
                {{ scope.row.isAdmin == "1" ? "是" : "否" }}
              </template>
            </el-table-column>
            <!-- <el-table-column prop="userStatus" label="状态" :min-width="$helper.getColumnWidth(4)" show-overflow-tooltip>
              <template slot-scope="scope">
                {{ scope.row.userStatus === "DISABLED" ? "停用" : "启用" }}
              </template>
            </el-table-column> -->
            <!-- 外包经办设置 -->
            <el-table-column prop="divisionCode" label="外包编号" :min-width="$helper.getColumnWidth(4)" show-overflow-tooltip v-if="queueType === 'OUTER'">
            </el-table-column>
            <el-table-column  prop="outOrgName" label="外包公司" :min-width="$helper.getColumnWidth(4)" show-overflow-tooltip  v-if="queueType === 'OUTER'">
            </el-table-column>
            <el-table-column prop="userStatus"  label="状态" :min-width="$helper.getColumnWidth(4)" show-overflow-tooltip v-if="queueType === 'OUTER'">
              <template slot-scope="scope">
                {{ scope.row.userStatus === "DISABLED" ? "停用" : "启用" }}
              </template>
            </el-table-column>
            <el-table-column prop="userStatus"  label="状态" :min-width="$helper.getColumnWidth(4)" show-overflow-tooltip v-if="queueType !== 'OUTER'">
              <template slot-scope="scope">
                {{ scope.row.userStatus === "DISABLED" ? "停用" : "启用" }}
              </template>
            </el-table-column>
          </template>
        </data-box-page-pick>
      </div>
    </div>
    <div class="operate-buttons">
      <el-button @click="close()">取消</el-button>
      <el-button @click="commit">确定</el-button>
    </div>
  </section>
</template>

<script lang="ts">
import Vue from "vue";
import Component from "vue-class-component";
import { Layout, Dependencies } from "~/core/decorator";
import { PageService } from "~/utils/page.service";
import { Emit, Prop, Watch } from "vue-property-decorator";
import { Action, State, Mutation, Getter, namespace } from "vuex-class";
import { UserService } from "~/services/management-service/user.service";
import DataBoxPagePick from "~/components/common/data-box-page-pick-queueList.vue";
import DepartmentTree from "~/components/system-manage/department-tree.vue";
import DataTree from "~/components/common/data-tree.vue";
import { QueueService } from "~/services/domain-service/queue-manage.service";
import { set } from "vue/types/umd";
import { TelephoneCollectionService } from "~/services/domain-service/telephone-collection-controller.service";
import { CaseQueueService } from "~/services/domain-service/case-queue.service";

@Layout("workspace")
@Component({
  components: {
    DepartmentTree,
    DataTree,
    DataBoxPagePick
  }
})
export default class AddAgent extends Vue {
  @Prop() private realArr
  @Prop({ default: false }) private isTeamUse;
  @Prop() private treeClose;
  @Prop() private queueId;
  @Prop() private queueType;
  @Dependencies(TelephoneCollectionService) private TelephoneCollectionService: TelephoneCollectionService;
  @Dependencies(CaseQueueService) private CaseQueueService: CaseQueueService;
  @Dependencies(UserService) private userService: UserService;
  @Dependencies(PageService) private pageService: PageService;
  @Dependencies(QueueService) private queueService: QueueService;
  @Prop() private departmentData;
  @Prop() private expandDefault;
  @Prop() private userIds;
  @Prop() private dialogVisible;
  private userDataSet = [];
  private userModel: any = {
    userName: "",
    realName: "",
    deptCode: "",
    isAdmin: "",
    handCode: "",
    // 外包
    outOrgName: "",
    id: ""
  };
  private selectionList: any[] = [];
  private selectAgent: any[] = [];
  private deptId: string = "";
  private dept: any = "";
  private deptCode: any = "";
  private selectListArr: any = [];
  private copy: any = [];
  private afterAgentChange: any;
  private dataFinds: any = [];

  // @Emit("close") private close() { this.emitGetAgentData(); }
  @Emit("close") private close() { 
    this.reset()
  }
  @Emit("getAgentData") private emitGetAgentData() {}

  @Watch("selectionList", { immediate: true }) private onCaseNumberChange(newVal, oldVal) {}
  
  private selectList(list) {
    this.selectListArr = list;
    this.selectAgent = list;
    console.log('list', list)
  }

  private getRowKeys(row) {
    return row.id;
  }

  private next() {
    this.$emit("next", this.selectListArr); 
  }

  // 复选框禁用
  private selectable(row) {
    if (this.queueType !== "OUTER") {
      return row.caseSwitch === "OPEN" && row.userStatus === 'ENABLED' ? true : false;
    } else {
      // return row.userStatus === "ENABLED" ? true : false;
      // return row.divisionStatus === "0" ? true : false; 
      // return row.caseSwitch === "OPEN" || row.userStatus === 'ENABLED' ? true : false;
      return row.caseSwitch === "OPEN" ? true : false;
    }
  }

  private created() {
    this.userModel.deptCode = this.expandDefault;
    // this.refreshData();
  }
  private refreshData() {
    // this.copy = [...this.reorganizeData(), ...this.copy];
    if (this.queueType === "SELF" || this.queueType === "LAWSUIT") { 
      this.NoOrgOut()  //  自催队列
    } else {
      this.OrgOut()  //  外包队列
    }
  }

  private NoOrgOut() {
    if(this.isTeamUse) {
      const UserDataId = this.realArr.map(item => {
        return item.id
      });
      this.userService.getAllUsers({...this.userModel,userIds: UserDataId}, this.pageService).subscribe(data => {
        this.userDataSet = data.map(item => {
          return { ...item, fixedCount: "", proportion: "" };
        });
      })
    } else {
      this.pageService.pageSize = 9999
      this.userService.getAllUsers({...this.userModel,userIds: this.userIds}, this.pageService).subscribe(data => {
        // 增加估值，比例的字段
        this.userDataSet = data.map(item => {
          return { ...item, fixedCount: "", proportion: "" };
        });
      });
    }
  }

  private OrgOut() {
    this.userService.getAllOutOrgInfo({ ...this.userModel, userIds: this.userIds },this.pageService).subscribe(data => {
        this.userDataSet = data
        this.userDataSet = data.map(item => {
          item.divisionStatus = String(item.divisionStatus);
          item.handCode = item.divisionCode;

          item.caseSwitch = item.divisionStatus;
          if(item.caseSwitch === '0'){
            item.caseSwitch = 'OPEN'
          } else if(item.caseSwitch === '1') { item.caseSwitch = 'CLOSE' }

          return { ...item, fixedCount: "", proportion: "" };
        });
      });
  }

  /**
   * 点击获取机构id
   */
  private onChange(value) {
    this.userModel.deptCode = value.deptCode;
    this.deptId = value.id;
    this.dept = value;
    this.refreshData();
  }

  private reorganizeData() {
    const arr = this.copy.map(v => v.id);
    const result: any = [];
    this.selectionList.forEach(v => {
      if (!arr.includes(v.id)) {
        result.push(v);
      }
    });
    return result;
  }

  //重置经办人
  private reset() {
    const dataBox: any = this.$refs["data-box"];
    dataBox.reset();
    this.userModel.realName = "";
    this.userModel.userName = "";
    this.userModel.handCode = "";
    this.pageService.pageIndex = 1;
    this.deptId = "";
    this.dept = "";
    // this.refreshData();
  }

  // 回显经办人
  private update(data) {
    this.userDataSet = []
    this.reset();
    const dataBox: any = this.$refs["data-box"];
    dataBox.updateSelectionList(data);  // 回显选中
    // dataBox.toggleRowSelection(data, true)
    this.copy = data;
    if(this.queueType === "OUTER"){
      data.map(item => {
        item.id = item.agentId;
        item.outOrgName = item.realName;
        item.divisionCode = item.handCode;
        // item.divisionStatus = item.caseSwitch;
      });
    }
  }

  //提交经办人
  private commit() {
    if (this.queueType !== "OUTER") {
      this.NoOrgOutCommit();  // 自催队列
    } else {
      this.OrgOutCommit();  // 外包队列
    }
  }

  private NoOrgOutCommit() {
      // this.selectAgent = [...this.reorganizeData(), ...this.copy];
      this.$emit("listenToChildEvent", this.selectAgent)
      this.close();
      this.userDataSet = []
      // this.$emit('getAllDepartmentData');
  }
  private OrgOutCommit() {
    this.selectAgent.map(item => {
      item.agentId = item.id;
      item.realName = item.outOrgName;
      item.handCode = item.divisionCode;
      item.caseSwitch = item.divisionStatus;
      if(item.caseSwitch === '0'){
        item.caseSwitch = 'OPEN'
      } else if(item.caseSwitch === '1') { item.caseSwitch = 'CLOSE' }
    });
    this.NoOrgOutCommit();
  }
}
</script>

<style lang="less" scoped>
.page.agent-manage {
  .col-span-2 {
    padding: 0;
  }
  .add-org {
    padding: 10px 20px;
    text-align: right;
    border-bottom: solid 1px #e4e4e4;
  }
  .org-tree {
    border: solid 1px #e4e4e4;
    min-height: 600px;
  }
  .col-span-10 {
    border: 1px solid #e4e4e4;
    border-left: none;
  }
  .col-span-12 {
    border: 1px solid #e4e4e4;
  }
  .title {
    padding-left: 10px;
    font-size: 16px;
  }
}
</style>
<style lang="less">
.team-note {
  .el-form-item__content {
    display: flex;
  }
}
.lockEndDate {
  margin-left: 64px;
}
.isTeamUse {
  .el-form-item__label {
    font-size: 14px !important;
    margin-left: -10px;
  }
  .el-form-item__content {
    margin-left: 0 !important;
  }
}
.queueRemark {
  margin-top: 20px;
}
.input-style {
  display: flex !important;
  .el-form-item__label {
    width: 106px !important;
  }
  .el-input {
    width: 100% !important;
  }
}
</style>
